// 引入 express 模块
const express = require("express");
// 创建 express 应用实例
const app = express();
// 解析 JSON 格式的请求体
app.use(express.json());

// 解析 URL 编码的请求体（表单提交）
app.use(express.urlencoded({ extended: true }));

// 引入配置文件
const config = require('./config');

// 定义根路由，处理 GET 请求
app.get("/", (req, res) => {
  // 响应客户端 "Hello World!"
  res.send("Hello World!");
});

// 引入 mysql 模块
const mysql = require('mysql');

// 创建数据库连接
const connection = mysql.createConnection(config.db);

// 连接到数据库
connection.connect();

// 查询图书列表
app.get("/test", (req, res) => {
    let sql = 'SELECT * FROM book';
    // if(req.query.bookName){
    //   sql = `select * from test where bookName like '%${req.query.bookName}%'`;
    // }
    connection.query(sql, (err, result) => {
      if(!err){
        res.json({
          status: 1,
          message: '查询成功',
          data: result
        })
      }else{
        res.json({
          status: 0,
          message: '查询失败',
          data: null
        })
      }
    })
});

// 添加图书
app.post("/add", (req, res) => {
  let sql = `insert into book (bookName, author, typeName, remarks) values ('${req.body.bookName}', '${req.body.author}', '${req.body.typeName}', '${req.body.remarks}')`;
  connection.query(sql, (err, result) => {
    if(!err){
      res.json({
        status: 1,
        message: '添加失败',
        data: null
      })
    }else{
      res.json({  
        status: 0,
        message: '添加成功',
        data: null
      })
    }
  })
})

// 修改图书
app.post('edit', (req, res) => {
  let sql = `update book set bookName = '${req.body.bookName}', author = '${req.body.author}', typeName = '${req.body.typeName}', remarks = '${req.body.remarks}' where id = ${req.body.id}`;
  connection.query(sql, (err, result) => {
    if(!err){
      res.json({
        status: 1,
        message: '修改失败',
        data: null
      })
    }else{
      res.json({  
        status: 0,
        message: '修改成功',
        data: null
      })
    }
  })
})

// 删除图书
app.post('delete', (req, res) => {
  let sql = `delete from book where id = ${req.query.id}`;
  connection.query(sql, (err, result) => {
    if(!err){
      res.json({
        status: 1,
        message: '删除失败',
        data: null
      })
    }else{
      res.json({  
        status: 0,  
        message: '删除成功',
        data: null  
      })
    }
  })
})

  

// 启动应用并监听 3000 端口
app.listen(3000, () => {
  console.log("示例应用正在监听 3000 端口 !");
});
